<?php

/**
 * 库存管理ajax类
 * @package  ajax
 * @subpackage  backend
 * @create by allen.qiang
 */
quanli_require('module/base/wmsHandler.class.php');

define("STORAGEID" , 2);

class ajax_goodsStore {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //获取库存列表信息
                    $this->searchList();
                    break;

                case 2: //对商品库存进行更新
                    $this->updateStorage();
                    break;
                    
                case 3: //商品库存列表
                    $this->goodsStorage();
                    break;

                case 4: //保存商品库存销售渠道分配
                    $this->goodsStoragePercent();
                    break;

                case 5: //保存渠道分配
                    $this->goodsStorageChannel();
                    break;

            }

        }

    }

    /**
     * 查询库存信息
     */
    private function searchList() {

        global $G_PGLOB;

        //排序
        $order = '';

        //分页
        $limit = '';

        //查询SQL
        $searchSql = '';

        $choice = $_REQUEST['choice'];
        $choiceValue = $_REQUEST['choiceValue'];
        
        if( !empty($choice) && !empty($choiceValue) ){

            /**
             * $choice   1.商品名称查询   2.商品SQU查询   3.商品编号查询
             */

            if( $choice == 1 ){

                $searchSql = ' WHERE gse.goodsName='.'\''.$choiceValue.'\'';

            }elseif ( $choice == 2 ){

                $searchSql = ' WHERE gse.product_code='.'\''.$choiceValue.'\'';

            }elseif ( $choice == 3 ){

                $searchSql = ' WHERE gse.product_mainID='.'\''.$choiceValue.'\'';

            }
        	
        }

        //组织返回的数据
        $result_array = array(
            'page'  => $_REQUEST['page'],
            'total' => 0,
            'rows'  => array()
        );

        if (isset($_REQUEST['rp']) && $_REQUEST['rp'] >= 1) {

            //排序
            if (isset($_REQUEST['sortname']) && !empty($_REQUEST['sortname']))
                $order = sprintf(' ORDER BY %s %s', $_REQUEST['sortname'], $_REQUEST['sortorder']);

            //分页
            if (!isset($_REQUEST['page']) || !is_numeric($_REQUEST['page']) || $_REQUEST['page'] <= 0)
                $_REQUEST['page'] = 1;

            $limit = sprintf(' LIMIT %d, %d', ($_REQUEST['page'] - 1) * $_REQUEST['rp'], $_REQUEST['rp']);

        } else {

            //排序
            if (isset($_REQUEST['sortname']) && !empty($_REQUEST['sortname']))
                $order = sprintf(' ORDER BY %s %s', $_REQUEST['sortname'], $_REQUEST['sortorder']);

        }
        
	    try {

            //统计总数
            $search_count = 'SELECT COUNT(*) num FROM wms_goodsstore wg INNER JOIN goods_sale_edit gse ON wg.goodsID = gse.goodsID '.$searchSql;
            $count_result = $G_PGLOB->DBCA->stmt_query( $search_count );
            $result_array['total'] = $count_result[0]->num;

            if( $count_result[0]->num == 0 )
                die( json_encode( $result_array ) );

            //查询数据
            $search_sql    = 'SELECT * FROM wms_goodsstore wg INNER JOIN goods_sale_edit gse ON wg.goodsID = gse.goodsID '.$searchSql.$order.$limit;
            $search_result = $G_PGLOB->DBCA->stmt_query( $search_sql );

	        if( $search_result ){
	        	
	        	foreach ( $search_result as $value){

                    //统计可售数量总库存
                    $enableSale_count = $G_PGLOB->DBCA->stmt_query( 'SELECT SUM(enableSaleAmount) enableSaleAmount FROM wms_goodsstore WHERE goodsID=?' , 'i' , $value->goodsID );

                    //统计锁定数量总库存
                    $lock_count = $G_PGLOB->DBCA->stmt_query( 'SELECT SUM(lockAmount) lockAmount FROM wms_goodsstore WHERE goodsID=?' , 'i' , $value->goodsID );

                    //统计坏货数量总库存
                    $bad_count = $G_PGLOB->DBCA->stmt_query( 'SELECT SUM(badAmount) badAmount FROM wms_goodsstore WHERE goodsID=?' , 'i' , $value->goodsID );

                    //统计销售数量总库存
                    $sale_count = $G_PGLOB->DBCA->stmt_query( 'SELECT SUM(saleAmount) saleAmount FROM wms_goodsstore WHERE goodsID=?' , 'i' , $value->goodsID );
	        		
	        		//此商品的总库存数
                    $storageTotal = 0;
	        		$storageTotal += $enableSale_count[0]->enableSaleAmount;
	        		$storageTotal += $lock_count[0]->lockAmount;
	        		$storageTotal += $bad_count[0]->badAmount;
	        		$storageTotal += $sale_count[0]->saleAmount;

                    if(  $G_PGLOB->has_permission(6008) ){

                        $result_array['rows'][] = array(
                            'id' => $value->goodsID,
                            'cell' => array(
                                //'<a href="javascript: goods.goodsStoreInfo(' . $value->goodsID . ');" >查看仓库</a>',
                                $value->product_code,
                                $value->goodsName,
                                $value->spec,
                                $storageTotal,
                                $enableSale_count[0]->enableSaleAmount,
                                $lock_count[0]->lockAmount,
                                $bad_count[0]->badAmount
                            )
                        );

                    } else {

                        $result_array['rows'][] = array(
                            'id' => $value->goodsID,
                            'cell' => array(
                                $value->product_code,
                                $value->goodsName,
                                $value->spec,
                                $storageTotal,
                                $enableSale_count[0]->enableSaleAmount,
                                $lock_count[0]->lockAmount,
                                $bad_count[0]->badAmount
                            )
                        );

                    }
	        		

	        	}
	        	
	        }
	        
	        echo json_encode($result_array);
            return;
        	
        }catch(Exception $e){
        	error_log($e->getMessage());
        	echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }
       
    }
    
    /**
     * 对商品库存进行更新
     */
    private function updateStorage() {

        global $G_PGLOB;

        $params = $_REQUEST['params'];

        //实例化公共仓库管理类
        $wmsHandler = new wmsHandler($G_PGLOB->DBCA);

        foreach( $params as &$value){
            $value['operator'] = $G_PGLOB->currentUserID;
        }

        //更新商品库存
        $result = $wmsHandler->UpdateStorage($params,0);

		echo json_encode( $result );
    }
    
   	//商品库存信息
    private function goodsStorage() {
    	global $G_PGLOB;
    	
    	if(!isset($_REQUEST['goodsID']) || !is_numeric($_REQUEST['goodsID'])){
        	echo json_encode(array('message'=>'参数错误' , 'code'=>400));
        	die(); 
    	}
    		
    	$commHandler = new commHandler( $G_PGLOB->DBCA );
    
        //查询仓库信息
        $goodsID 	 = $_REQUEST['goodsID'];

        //查询
        $result = $G_PGLOB->DBCA->stmt_query('SELECT wg.*,ws.`storeName`,gs.`goodsName`,gs.`product_code`,gs.`spec` FROM wms_goodsstore  wg
											  INNER JOIN goods_sale_edit gs ON gs.`goodsID`=wg.`goodsID`
											  INNER JOIN `wms_store` ws ON wg.`storeID`=ws.`storeID` WHERE wg.goodsID =? ' , 'i' , $goodsID);						        
        //组织返回的数据
        $result_array = array(
            'page'  => $_REQUEST['page'],
            'total' => 1,
            'rows'  => array()
        );
		
        if( $result ){
        	foreach($result as &$r_l) {
        		$id =  $r_l->goodsID  . '_' . $r_l->storeID  ;
	    		$result_array['rows'][] = array(
	                'id'   => $id,
	                'cell' => array(
	                    '<a href="javascript: void(0);" onclick="editOne(\'' . $id . '\')" id="edit_' . $id . '" >修改</a> &nbsp;&nbsp;'.
	                    '<a href="javascript: void(0);" onclick="cancelOne(\'' . $id . '\');" id="cancel_' . $id . '"  style="display:none;">取消</a>&nbsp;&nbsp;'.
	                    '<a href="javascript: void(0);" onclick="simpleSave(\'' . $id . '\');" id="save_' . $id . '"  style="display:none;">保存</a>',
	                    $r_l->product_code,
	                    $r_l->goodsName,
	                    $r_l->spec,
	                    $r_l->storeName,
	                    '<span id="amount_' . $id . '">' . $r_l->enableSaleAmount . '</span>'
	                )
	           );
        	}
    	}
        echo json_encode($result_array);
    }

    /**
     * 商品销售渠道分配
     */
    function goodsStoragePercent(){

        global $G_PGLOB;

        if(!isset($_REQUEST['data']) || empty($_REQUEST['data'])){
            echo json_encode(array('message'=>'参数错误' , 'code'=>400));
            die();
        }

        //实例化公共仓库管理类
        $wmsHandler = new wmsHandler($G_PGLOB->DBCA);

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //保存商品销售渠道库存分配
        $result = $wmsHandler->saveGoodsStoragePercent($_REQUEST);

        echo json_encode( $result );

    }

    /**
     * 保存渠道分配调整
     */
    function goodsStorageChannel(){

        global $G_PGLOB;

        if(!isset($_REQUEST['data']) || empty($_REQUEST['data'])){
            echo json_encode(array('message'=>'参数错误' , 'code'=>400));
            die();
        }

        //实例化公共仓库管理类
        $wmsHandler = new wmsHandler($G_PGLOB->DBCA);

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //保存渠道分配调整
        $result = $wmsHandler->saveGoodsStorageChannel($_REQUEST);

        echo json_encode( $result );

    }
    
}